package y2019.date0525.event;

import java.util.ArrayList;
import java.util.HashMap;


public class EventBus {
    interface IEvent {
        void callBack(String key, Object... data);
    }

    private HashMap<String, ArrayList<IEvent>> eventMap;

    public EventBus() {
        eventMap = new HashMap<>();
    }

    public void on(String key, IEvent iEvent) {
        ArrayList<IEvent> events = eventMap.get(key);
        if (events == null) {
            events = new ArrayList<>();
            events.add(iEvent);
            eventMap.put(key, events);
        } else {
            events.add(iEvent);
        }
    }

    public void off(String key) {
        eventMap.remove(key);
    }

    public void offAll() {
        eventMap.clear();
    }

    public void once(String key, IEvent iEvent) {
        //保持最新
        ArrayList<IEvent> events = new ArrayList<>();
        events.add(iEvent);
        eventMap.put(key, events);
    }

    public void emit(String key, Object... data) {
        ArrayList<IEvent> events = eventMap.get(key);
        if (events == null) {
            return;
        }
        for (int i = 0; i < events.size(); i++) {
            events.get(i).callBack(key, data);
        }
    }
}
